package cn.ycoz.cloud.windspeed.action;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.*;

@Controller
public class DynamicServiceAction {


    @GetMapping(value = "/service/{service}",produces = "text/plain;charset=UTF-8")
    public ResponseEntity dynamicService(@PathVariable("service") String service) throws IOException, TemplateException {
        HttpHeaders headers = new HttpHeaders();
        Writer writer = new StringWriter();
        Template template ;

        Map<String, Object> root = new HashMap<>();
        Map<String, String> mx = new HashMap<>();
        mx.put("alingluo", "阿灵罗");
        mx.put("lling", "罗零");
        root.put("mx", mx);

        switch (service) {
            case "testJson":
                headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
                template = configuration.getTemplate("json/list.ftl");
                template.process(root, writer);
                break;
            case "testXml":
                headers.setContentType(MediaType.valueOf("text/xml;charset=UTF-8"));
                template = configuration.getTemplate("xml/list.ftl");
                template.process(root, writer);
                break;
            case "other":
                headers.setContentType(MediaType.valueOf("text/plain;charset=UTF-8"));

                root.put("message", "abcdefghijklmnopqrstwuvxyz1234567890ABCDEFGHIJKLMNOPQRSTWUVXYZ");

                template = configuration.getTemplate("other/list.ftl");
                template.process(root, writer);
                break;
            default:
                return new ResponseEntity(HttpStatus.NOT_FOUND);
        }

        return  new ResponseEntity<>(writer.toString(), headers, HttpStatus.OK);
    }

    @Autowired
    Configuration configuration;
}
